<script lang="ts" setup>
import type { StateType } from './types';

import { computed } from 'vue';
import { useRoute } from 'vue-router';
import Draggable from 'vuedraggable';

import { Page } from '@vben/common-ui';
import { useTabs } from '@vben/hooks';
import { $t } from '@vben/locales';
import { useTitle } from '@vueuse/core';
import {
  Card,
  message,
  Input,
  Textarea,
  Button,
} from 'ant-design-vue';
import Icon from '#/components/Icons';
import dayjs from 'dayjs';
import { storeToRefs } from 'pinia';
import Upload from "#/components/Upload";

import { useVbenForm } from '#/adapter/form';
import { postPage_distributor, getPageInfo_distributor} from '#/api/portal/distributor';
import { usePreferencesStore } from '#/store';

const route = useRoute();

const { setTabTitle, closeCurrentTab } = useTabs();

const index: any = computed(() => {
  return route.params?.id ?? -1;
});
const router = useRouter();

const routeMeta = router.currentRoute.value.meta;
const routeTitle = routeMeta.title.replace('管理', '');
const preferencesStore = usePreferencesStore();
const { title } = storeToRefs(preferencesStore);


const pageTitle =
  Number.parseInt(index.value, 10) === 0
    ? `新增${routeTitle}`
    : `No.${index.value} - 编辑${routeTitle}`;
setTabTitle(pageTitle);
useTitle(`${pageTitle} - ${title.value}`);

const disabled = ref(true);
const activeKey = ref('1');
const state: StateType = reactive({
  form: {
    title: '',
    is_checked: false,
    content:[],
  },
});

const [BasicForm, BasicFormApi] = useVbenForm({
  handleSubmit: onSubmit,
  resetButtonOptions: {
    show: false,
  },
  schema: [
    {
      component: 'Input',
      dependencies: {
        show: false,
        // 随意一个字段改变时，都会触发
        triggerFields: ['id'],
      },
      fieldName: 'id',
      label: 'ID',
    
    },
    {
      component: 'Textarea',
      defaultValue: '',
      dependencies: {
        trigger: (values) => {
            disabled.value = !values.title;
            state.form.dealer_standard_content = values.dealer_standard_content;
            state.form.dealer_standard_example = values.dealer_standard_example;
            state.form.questions_content = values.questions_content;
            state.form.questions_images = values.questions_images;
        
        },
        // 随意一个字段改变时，都会触发
        triggerFields: [
          'id',
          'dealer_standard_content',
          'dealer_standard_example',
          'is_checked',
          'questions_content',
          'questions_images'
        ],
      },
       componentProps: {
        placeholder: $t('page.common.Please Enter'),
        style: {
          minHeight: '200px', // 设置最小高度为 100px
        },
      },
      fieldName: 'dealer_standard_content',
      label: $t('page.common.Description'),
      rules: 'required',
    },


    {
      component: 'dealer_standard_example',
      defaultValue: [{title:'',images:[{'url':'','id':''}]}],
      componentProps: {
        placeholder: $t('page.common.Please Enter'),
      },
      fieldName: 'dealer_standard_example',
      label:  $t('admin.case'),
    },
     {
      component: 'Upload',
      defaultValue: [{url:'',id:''}],
      componentProps: {
        placeholder: $t('page.common.Please Enter'),
      },
      fieldName: 'questions_images',
      label:  $t('admin.issueImage'),
    },
       {
      component: 'questions_content',
      defaultValue: [{question:'',question_answer:''}],
      componentProps: {
        placeholder: $t('page.common.Please Enter'),
      },
      fieldName: 'questions_content',
      label:  $t('admin.issue'),
    },
       
       
  ],
});

const contentList = ref([
  { title: '', images: [{ url: '', id: '' }], is_checked: false }
]);
const questions_content_list=ref([
 {question:'',question_answer:''}
]);


async function onSubmit() {
console.log(contentList.value);

  updateForm();
  updateQuestion();
  function showMsg(msg: string) {
    message.success(msg);
  }
  const values: any = state.form;

  if (values.id) {
    const { msg } = await postPage_distributor(values);
    showMsg(msg);
  } else {
    delete values.id;
    const { msg } = await postPage_distributor(values);
    showMsg(msg);
  }
}
async function onGetPage() {
  const { data } = await getPageInfo_distributor();

  data.post = {
    id: data?.id ?? undefined,
    dealer_standard_content: data?.dealer_standard_content ?? '',
    dealer_standard_example: data?.dealer_standard_example ?? [{title:'',images:[{'url':'','id':''}],is_checked:false}],
    questions_images: data?.questions_images ?? [{url:'',id:''}],
    questions_content: data?.questions_content ?? [{question:'',question_answer:''}],


  };
  
  state.form = data.post;
  BasicFormApi.setValues({ ...state.form});
const example = data.post.dealer_standard_example;

contentList.value = Array.isArray(example) &&example.length > 0 &&!(example.length === 1 && example[0] === '') ? JSON.parse(JSON.stringify(example)) : [{ title: '', images: [{ url: '', id: '' }], is_checked: false }];

 const content1 = data.post.questions_content;
questions_content_list.value =Array.isArray(content1) &&content1.length > 0 &&!(content1.length === 1 && content1[0] === '') ? JSON.parse(JSON.stringify(content1)): [{ title: '', images: [{ url: '', id: '' }], is_checked: false }];


}

onMounted(async () => {
  await onGetPage();
});


// 更新 name
function onUpdateName(index, value) {
  contentList.value[index].name = value
  updateForm()
}

// 更新 content
function onUpdateContent(index, value) {
  contentList.value[index].content = value
  updateForm()
}
function createContentItem() {
  return {
    title: '',
    images: [{ url: '', id: '' }],
    is_checked: false
  };
}
// 添加一项

function addContentItem() {
 
  contentList.value.push(createContentItem());
  updateForm();
}
function removeContentItem(index) {
    if (contentList.value.length <= 1) {return;}
  contentList.value.splice(index, 1) // 删除指定下标的项
  updateForm()                       // 同步到表单
}


// 同步到表单字段
function updateForm() {
  state.form.dealer_standard_example = JSON.parse(JSON.stringify(contentList.value));
  BasicFormApi.setFieldValue('dealer_standard_example', JSON.parse(JSON.stringify(contentList.value))) // 深拷贝同步表单

}


function createQuestionItem() {
  return {question:'',question_answer:''};
}
function addQuestion(){
   questions_content_list.value.push(createQuestionItem());
   updateQuestion();
}

function removeQuestionItem(){
  if(questions_content_list.value.length<=1) return;
   questions_content_list.value.splice(index, 1) // 删除指定下标的项
   updateQuestion();
}

function updateQuestion() {
    state.form.questions_content = JSON.parse(JSON.stringify(questions_content_list.value));
BasicFormApi.setFieldValue('questions_content', JSON.parse(JSON.stringify(questions_content_list.value))) // 深拷贝同步表单
 
}
function onUpdatequestion(index,value){
   if (questions_content_list.value[index]) {
  questions_content_list.value[index].question = value;
}
  updateQuestion()
}

function onUpdateanswer(index,value){
   if (questions_content_list.value[index]) {
      questions_content_list.value[index].question_answer = value;
    }
  updateQuestion()
}

</script>

<template>
  <Page>
    <Card :title="`${routeTitle} `+$t('page.common.Details')">
      <BasicForm>

        <template #dealer_standard_example>
          <div class="content_s">
                <Card>
                   <Draggable v-model="contentList" item-key="id"  handle=".cursor-pointer" class="grid grid-cols-1  md:grid-cols-2 lg:grid-cols-2 xl:grid-cols-2 gap-2">
                        <template #item="{ element, index }">
                          <div class="flex  items-start" style="margin-top: 16px; padding: 16px; border-radius: 8px; box-shadow: 0 2px 8px rgba(0,0,0,0.1);">
                            <!-- 图片上传 -->
                            <Upload
                              list-type="picture-card"
                              v-model="element.images"
                              :tips="'尺寸:440x250px'"
                              style="flex-shrink: 0;"
                            />

                            <!-- 表单内容 -->
                            <div class="flex flex-col gap-3 w-full">
                              <!-- 标题输入 -->
                              <Textarea
                                v-model:value="element.title"
                                :placeholder="$t('page.common.Please Enter')"
                                class="w-full"
                                rows="4"
                                @input="onUpdateName(index, element.title)"
                              />

                              <!-- 删除按钮 -->
                              <div class="flex gap-6 justify-end items-center">
                                <Button danger type="dashed" @click="removeContentItem(index)">{{$t('page.common.Delete')}}</Button>
                                <Button type="dashed" @click="addContentItem">{{$t('page.common.Add')}}</Button>
                                <Icon icon="ri:menu-2-line"  class="cursor-pointer"  title="点击拖动" />
                              </div>
                            </div>
                          </div>
                        </template>
                      </Draggable>
                       


                        
                 </Card>




             

               <div>
                
               
               </div>
          </div>  
          
          
        </template>




         <template #questions_content>
              <div class="content_s">
                    <Card>
                          <Draggable v-model="questions_content_list" handle=".cursor-pointer" class="grid grid-cols-1 gap-6">
                            <template #item="{ element, index }">
                              <div
                                class="flex gap-4 items-start flex-col bg-white p-4 rounded-lg shadow"
                                style="margin-top: 16px;"
                              >
                                <Textarea
                                 placeholder="请输入问题"
                                  v-model:value="element.question"
                                  class="w-full border p-3"
                                  rows="4"
                                  @input="onUpdatequestion(index, element.question)"
                                ></Textarea>
                                  <Textarea
                                  placeholder="请输入答案"
                                  v-model:value="element.question_answer"
                                  class="w-full border p-3"
                                  rows="6"
                                  @input="onUpdateanswer(index, element.question_answer)"
                                ></Textarea>
                              

                            
                            
                                <div class="flex gap-6 justify-end items-center w-full">
                                  <Button danger type="dashed" @click="removeQuestionItem(index)">{{$t('page.common.Delete')}}</Button>
                                  <Button type="dashed" @click="addQuestion">{{$t('page.common.Add')}}</Button>
                                  <Icon icon="ri:menu-2-line" class="cursor-pointer"  title="点击拖动" />
                                </div>
                              </div>
                            </template>
                          </Draggable>
                    </Card>
              </div>  
          
          
        </template>
      </BasicForm>
    </Card>
  </Page>
</template>

<style lang="scss">
      .content_s{
        display: flex;
        gap: 25px;
        width: 100%;
        flex-direction: column;
         .input ,.textarea,.submit{
            width: 100%;
            display: block;
         }
         .textarea{
            min-height: 100px;
         }
      }
</style>>
